<template>
  <var-form @submit="handleSubmit">
    <var-space direction="column" :size="[14, 0]">
      <var-input
        autofocus
        placeholder="手机号"
        :rules="[v => !!v || '手机号不能为空']"
        v-model="formData.phone"
      />
      <var-input
        placeholder="验证码"
        :rules="[v => !!v || '验证码不能为空']"
        v-model="formData.code"
      >
        <template #append-icon>
          <var-link
            v-if="showSendCode"
            @click="getCode"
            type="primary"
            underline="none"
            >获取验证码</var-link
          >
          <var-countdown
            v-else
            @end="showSendCode = true"
            format="重发(ss)"
            :time="60 * 1000"
          />
        </template>
      </var-input>
    </var-space>
    <div class="link">
      <var-link to="/login" type="primary" underline="none">密码登录</var-link>
      <var-link to="/register" type="primary" underline="none"
        >立即注册</var-link
      >
    </div>
    <var-button style="width: 100%" type="primary" native-type="submit"
      >登录</var-button
    >
  </var-form>
</template>

<script setup lang="ts">
import { codeLogin, sendCode } from '@/api'

const router = useRouter()
const route = useRoute()

const showSendCode = ref(true)
const getCode = async () => {
  if (formData.value.phone.trim() === '') {
    Snackbar['error']('请输入手机号')
    return
  }
  await sendCode(formData.value.phone)
  showSendCode.value = false
}

const formData = ref({
  phone: '13511111111',
  code: ''
})

const handleSubmit = async valid => {
  if (!valid) return
  const res = await codeLogin(formData.value)
  res && localStorage.setItem('token', res)
  Snackbar['success']('登录成功')

  router.push(route.query.returnUrl ? route.query.returnUrl : '/home')
}
</script>

<style scoped lang="scss">
span {
  font-size: 14px;
}
</style>
